import {useCallback, useState} from "react";
import Taro from '@tarojs/taro';
import classNames from "classnames";
import {View, Input, Image} from "@tarojs/components";
import SearchIcon from '@/assets/imgs/search-icon.png';
import CloseIcon from '@/assets/imgs/close.png';
import styles from './index.module.scss';
import {SearchItem} from "./components/search-item";

export default function (){

  const [searchWords, setSearchWords] = useState('');

  const lists = ['火锅粉','麻辣烫','炸串','烧烤','炸鸡','炸鸡腿'];

  const cancel = useCallback(()=>{
    Taro.navigateBack();
  }, []);

  const confirm = useCallback(()=>{
    Taro.navigateTo({url: '/pages/search-list/index'});
  }, []);

  const onInput = useCallback((e)=>{
    setSearchWords(e.detail.value);
  }, []);

  const clearWords = useCallback(()=>{
    setSearchWords('');
  }, []);

  const searchHistory = useCallback((words: string)=>{
    setSearchWords(words);
    confirm();
  }, [confirm]);

  const hasWords = searchWords.length > 0;

  return (
    <View className={styles.searchWrapper}>
      <View className={styles.headPart}>
        <View className={styles.inputWrapper}>
          <Image className={styles.search} src={SearchIcon} mode='aspectFit' />
          <Input
            placeholder='炸串、烧烤、冰粉等'
            onConfirm={confirm}
            onInput={onInput}
            value={searchWords}
          />
          <Image
            src={CloseIcon}
            mode='aspectFit'
            style={{display: hasWords ? 'block' : 'none'}}
            onClick={clearWords}
          />
        </View>
        {
          hasWords ? (
            <View className={classNames(styles.btn, styles.confirm)} onClick={confirm}>确认</View>
          ) : (
            <View className={classNames(styles.btn)} onClick={cancel}>取消</View>
          )
        }
      </View>
      <View className={styles.searchHistory}>
        <View className={styles.title}>最近搜索</View>
        <View className={styles.listContainer}>
          {
            lists.map(item=>(
              <SearchItem key={item} title={item} onClick={searchHistory} />
            ))
          }
        </View>
      </View>
    </View>
  );
}
